package com.skywolf.chem.manager;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.ServiceException;
import com.skywolf.chem.common.sysconfig.pojo.vo.PageVO;
import com.skywolf.chem.common.sysconfig.response.RespData;
import com.skywolf.chem.customer.entity.Signup;
import com.skywolf.chem.customer.param.SignupDto;
import com.skywolf.chem.customer.service.ISignupService;
import com.skywolf.chem.live.entity.Live;
import com.skywolf.chem.live.param.VideoDto;
import com.skywolf.chem.live.service.ILiveService;
import com.skywolf.chem.manager.param.*;
import com.skywolf.chem.tencent.service.ImService;
import com.skywolf.chem.tencent.service.LiveAuth;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by pei_pei on 2020/12/11.
 */
@RestController
@RequestMapping("/manager/live")
@Api(value = "管理后台-直播相关", description = "管理后台-直播相关")
public class LiveManagerController {
    Logger logger = LoggerFactory.getLogger(LiveManagerController.class);

    @Autowired
    ILiveService liveService;

    @Autowired
    LiveAuth liveAuth;

    @Autowired
    ISignupService signupService;


    @Autowired
    ImService imService;

    DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @ApiOperation(value = "直播列表",notes = "直播列表")
    @RequestMapping(value = "/liveList",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<PageVO<VideoDto>> liveList(HttpServletRequest request, @RequestBody @Validated LiveQueryDto queryParam) {
        PageVO<VideoDto> page = liveService.pageLiveListManager(queryParam);
        return RespData.success(page);
    }

    @ApiOperation(value = "直播报名列表",notes = "直播报名列表")
    @RequestMapping(value = "/liveSignUpList",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<PageVO<SignupDto>> liveSignUpList(HttpServletRequest request, @RequestBody @Validated LiveSignUpQueryDto queryParam) {
        PageVO<SignupDto> page = liveService.pageLiveSignUpListManager(queryParam);
        return RespData.success(page);
    }


    @ApiOperation(value = "更新直播",notes = "更新直播")
    @RequestMapping(value = "/updateLive",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<String> updateLive(HttpServletRequest request, @RequestBody @Validated LiveManagerDto param) {
        Live live = new Live();
        BeanUtils.copyProperties(param,live);
        if(param.getTimeSelValue()!=null && param.getTimeSelValue().size()>0){
            String time = param.getTimeSelValue().get(0);
            String[] times = time.split(" ");
            LocalDateTime ldt = LocalDateTime.parse(times[0]+" 00:00:00",dtf);
            live.setSignTime(ldt);

            time = param.getTimeSelValue().get(1);
            times = time.split(" ");
            ldt = LocalDateTime.parse(times[0]+" 23:59:59",dtf);
            live.setEndTime(ldt);
        }
        if(StringUtils.isNotBlank(param.getLiveTime())){
            String time = param.getLiveTime();
            String[] times = time.split(" ");
            LocalDateTime ldt = LocalDateTime.parse(times[0]+" 00:00:00",dtf);
            live.setLiveTime(ldt);
        }
        liveService.updateById(live);
        return RespData.success();
    }

    @ApiOperation(value = "添加直播",notes = "添加直播")
    @RequestMapping(value = "/addlive",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<String> addlive(HttpServletRequest request, @RequestBody @Validated LiveManagerDto param) {
        Live live = new Live();
        BeanUtils.copyProperties(param,live);
        if(param.getTimeSelValue()!=null && param.getTimeSelValue().size()>0){
            String time = param.getTimeSelValue().get(0);
            String[] times = time.split(" ");
            LocalDateTime ldt = LocalDateTime.parse(times[0]+" 00:00:00",dtf);
            live.setSignTime(ldt);

            time = param.getTimeSelValue().get(1);
            times = time.split(" ");
            ldt = LocalDateTime.parse(times[0]+" 23:59:59",dtf);
            live.setEndTime(ldt);
        }else{
            return RespData.failResult("请选择直播报名时间！");
        }
        if(StringUtils.isNotBlank(param.getLiveTime())){
            String time = param.getLiveTime();
            LocalDateTime ldt = LocalDateTime.parse(time,dtf);
            live.setLiveTime(ldt);
        }else{
            return RespData.failResult("请选择开始直播时间！");
        }
        liveService.save(live);
        return RespData.success();
    }


    @ApiOperation(value = "根据直播id，查询直播详情",notes = "根据直播id，查询直播详情")
    @RequestMapping(value = "/getLiveInfo",method = {RequestMethod.GET},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<LiveManagerDto> getLiveInfo(@RequestParam(value = "id",required = true) Long id) {
        Live live = liveService.getById(id);
        LiveManagerDto dto = new LiveManagerDto();
        BeanUtils.copyProperties(live,dto);
        List<String> times = new ArrayList<>();
        if(live.getSignTime()!=null){
            times.add(dtf2.format(live.getSignTime()));
        }
        if(live.getEndTime()!=null){
            times.add(dtf2.format(live.getEndTime()));
        }
        dto.setTimeSelValue(times);
        if(live.getLiveTime()!=null){
            dto.setLiveTime(dtf.format(live.getLiveTime()));
        }
        return RespData.success(dto);
    }


    @ApiOperation(value = "删除直播",notes = "删除直播")
    @RequestMapping(value = "/delLiveById",method = {RequestMethod.GET},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<String> delLiveById(@RequestParam(value = "id",required = true) Long id) {
        liveService.removeById(id);
        return RespData.success("success");
    }

    @ApiOperation(value = "直播上下架",notes = "直播上下架")
    @RequestMapping(value = "/updateStatus",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<String> updateStatus(HttpServletRequest request, @RequestBody @Validated LiveManagerDto param) {
        Live live = new Live();
        live.setId(param.getId());
        live.setStatus(param.getStatus());
        liveService.updateById(live);
        return RespData.success();
    }

    @ApiOperation(value = "直播报名审批",notes = "直播报名审批")
    @RequestMapping(value = "/updateSignUpStatus",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<String> updateSignUpStatus(HttpServletRequest request, @RequestBody @Validated LiveSignUpManagerDto param) {
        Signup signup = new Signup();
        signup.setId(param.getId());
        signup.setStatus(param.getStatus());
        signupService.updateById(signup);
        return RespData.success();
    }


    @ApiOperation(value = "生成直播信息",notes = "生成直播信息")
    @RequestMapping(value = "/createLiveInfo",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<LiveTXDto> createLiveInfo(HttpServletRequest request, @RequestBody @Validated LiveTXDto param) {
        try{
            String pullUrl = liveAuth.getPullUrl(param.getId());
            String pushUrl = liveAuth.getPushUrl(param.getId());
            if(pullUrl==null || pushUrl==null){
                return RespData.failResult("直播信息生成失败！");
            }
            Live live = liveService.getById(param.getId());
            String groupId = "";
            if(StringUtils.isBlank(live.getGroupId())){
                groupId = imService.getGroupId(param.getId()+"");
            }

            Live model = new Live();
            model.setId(param.getId());
            model.setPushFlow(pushUrl);
            model.setPullFlow(pullUrl);
            if(StringUtils.isNotBlank(groupId)){
                model.setGroupId(groupId);
            }
            liveService.updateById(model);

            LiveTXDto modelRe = new LiveTXDto();
            modelRe.setPullFlow(pullUrl);
            modelRe.setPushFlow(pushUrl);
            return RespData.success(modelRe);
        }catch (Exception e){
            e.printStackTrace();
        }
        return RespData.failResult("直播信息生成失败！");
    }

}
